import { MinimalButton, Store } from "../../core";

import ExitFullScreenIcon from "./ExitFullScreenIcon";
import { exitFullScreen, getFullScreenElement } from "./fullScreen";
import StoreProps from "./StoreProps";
import { FC, useEffect, useState } from "react";

const ExitFullScreenButton: FC<{
  store: Store<StoreProps>;
}> = ({ store }) => {
  const [isFullScreen, setFullScreen] = useState(false);

  const handleFullScreen = (fullScreen: boolean) => {
    setFullScreen(fullScreen);
  };

  const handleExitFullScreen = () => {
    setFullScreen(false);

    const getPagesContainer = store.get("getPagesContainer");
    if (!getPagesContainer) {
      return;
    }

    const pagesEle = getPagesContainer();
    if (!pagesEle) {
      return;
    }

    const ele = getFullScreenElement();
    if (ele && ele === pagesEle) {
      exitFullScreen(document)?.finally(() => {});
    }
  };

  useEffect(() => {
    store.subscribe("isFullScreen", handleFullScreen);
    return (): void => {
      store.unsubscribe("isFullScreen", handleFullScreen);
    };
  }, []);

  return (
    <>
      {isFullScreen && (
        <div className="rpv-full-screen__exit-button">
          <div className="rpv-full-screen__exit-button-content">
            <MinimalButton onClick={handleExitFullScreen}>
              <ExitFullScreenIcon />
            </MinimalButton>
          </div>
        </div>
      )}
    </>
  );
};

export default ExitFullScreenButton;
